﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Messenger.DataAccess.Attributes
{
    /// <summary>
    /// Email validation
    /// Created by: Dinh Quoc Vuong
    /// Created date: Oct 6th 2011
    /// </summary>
    public class EmailValidationAttribute : ValidationBaseAttribute
    {
        #region Properties
        /// <summary>
        /// Email validation expression
        /// </summary>
        private string _regExp = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                   @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                   @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
        #endregion

        #region constuctors
        public EmailValidationAttribute() : base() { }

        public EmailValidationAttribute(string message)
            : base(message)
        {

        }
        #endregion

        #region overrides
        /// <summary>
        /// Validate text length
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override bool Validate(object obj)
        {
            bool isValid = false;
            string value = (string)obj;
            isValid = !string.IsNullOrEmpty(value);

            if (isValid)
            {
                isValid = Regex.IsMatch(value, _regExp);
            }
            return isValid;
        }

        /// <summary>
        /// Get error message
        /// </summary>
        /// <param name="propertyName">your property name</param>
        /// <returns></returns>
        public override string GetErrorMessage(string propertyName = null)
        {
            string msg = Message;
            if (msg == null)
            {
                msg = "Property " + propertyName + " is not an valid email.";
            }
            return msg;
        }
        #endregion
    }
}
